package com.travel.controller.user;

import com.travel.common.UserContext;
import com.travel.constant.UserConstant;
import com.travel.entity.dto.LoginRequestDTO;
import com.travel.entity.dto.UserRegisterDTO;
import com.travel.entity.dto.UserUpdateDTO;
import com.travel.entity.vo.LoginResponseVo;
import com.travel.entity.vo.UserVo;
import com.travel.result.Result;
import com.travel.service.impl.UserServiceImpl;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

/**
 * @Author:Jasenon_ce
 * @Date: 2025/03/13/下午4:15
 */
@RestController
@RequestMapping("/user")
@Api(tags = "普通用户相关操作")
public class UserController {

    @Resource
    private UserServiceImpl userServiceImpl;

    @ApiOperation("用户注册")
    @RequestMapping("/register")
    public Result<?> register(@Validated @RequestBody UserRegisterDTO userRegisterDTO) throws InstantiationException, IllegalAccessException {
        userServiceImpl.userRegister(userRegisterDTO);
        return Result.success(UserConstant.USER_REGISTER_SUCCESS);
    }

    @ApiOperation("用户登录")
    @RequestMapping("/login")
    public Result<?> login(@Validated @RequestBody LoginRequestDTO loginRequestDTO) throws InstantiationException, IllegalAccessException {
        LoginResponseVo loginResponseVo = userServiceImpl.userLogin(loginRequestDTO);
        return new Result<>(200,UserConstant.USER_LOGIN_SUCCESS,loginResponseVo);
    }
    
    @ApiOperation("更新用户信息")
    @PutMapping("/update")
    public Result<UserVo> updateUserInfo(@Validated @RequestBody UserUpdateDTO userUpdateDTO, HttpServletRequest request) {
        // 从UserContext获取当前用户ID
        Long userId = UserContext.getUserId();
        
        // 如果上下文中没有用户ID，返回未认证错误
        if (userId == null) {
            return Result.fail(401, UserConstant.USER_NOT_LOGIN);
        }
        
        // 调用服务更新用户信息
        UserVo updatedUser = userServiceImpl.updateUserInfo(userId, userUpdateDTO);
        return Result.success(updatedUser);
    }
    
    @ApiOperation("获取当前用户信息")
    @GetMapping("/info")
    public Result<UserVo> getUserInfo() {
        // 从UserContext获取当前用户ID
        Long userId = UserContext.getUserId();
        
        // 如果上下文中没有用户ID，返回未认证错误
        if (userId == null) {
            return Result.fail(401, UserConstant.USER_NOT_LOGIN);
        }
        
        // 这里调用一个新方法来获取用户信息，你可能需要在UserService中添加这个方法
        return Result.success( userServiceImpl.getUser());
    }
}
